/**
 * NASKI代付接口测试脚本
 *
 * 使用方式:
 * bun run scripts/test-naski-payout.ts
 */

import { createNaskiPayService } from '../src/services/naskiPayService';
import { Logger } from '../src/utils/logger';

async function testNaskiPayout() {
  console.log('========================================');
  console.log('NASKI代付接口测试');
  console.log('========================================\n');

  try {
    // 检查环境变量配置
    console.log('1. 检查环境变量配置...');
    const requiredEnvVars = [
      'NASKI_MERCHANT_ID',
      'NASKI_SECRET_KEY',
      'NASKI_BASE_URL',
      'NASKI_NOTIFY_URL'
    ];

    const missingVars = requiredEnvVars.filter(varName => !process.env[varName]);
    if (missingVars.length > 0) {
      console.error('❌ 缺少必要的环境变量:', missingVars.join(', '));
      console.error('请在 .env 文件中配置以下变量:');
      console.error('  NASKI_MERCHANT_ID=你的商户号');
      console.error('  NASKI_SECRET_KEY=你的密钥');
      console.error('  NASKI_BASE_URL=https://naski.gctpk.com');
      console.error('  NASKI_NOTIFY_URL=你的回调地址');
      console.error('  NASKI_PUBLIC_KEY=RSA公钥(可选,用于验证回调)');
      process.exit(1);
    }

    console.log('✅ 环境变量配置检查通过');
    console.log(`   商户号: ${process.env.NASKI_MERCHANT_ID}`);
    console.log(`   API地址: ${process.env.NASKI_BASE_URL}`);
    console.log(`   回调地址: ${process.env.NASKI_NOTIFY_URL}\n`);

    // 创建NASKI服务实例
    console.log('2. 创建NASKI服务实例...');
    const naskiService = createNaskiPayService();
    console.log('✅ NASKI服务实例创建成功\n');

    // 生成测试订单号
    const testOrderId = naskiService.generateOrderId();
    console.log('3. 生成测试订单号...');
    console.log(`✅ 订单号: ${testOrderId}\n`);

    // 测试代付下单
    console.log('4. 测试代付下单...');
    console.log('【测试参数】');
    console.log('  金额: 100 THB');
    console.log('  支付方式: BankTransfer');
    console.log('  收款人: Test User');
    console.log('  银行卡号: 1234567890');
    console.log('  银行代码: 004 (KBANK)\n');

    const payoutRequest = {
      amount: 100,
      paymentMethod: 'BankTransfer' as const,
      orderId: testOrderId,
      receiverName: 'Test User',
      receiverBankCard: '1234567890',
      bankCode: '004', // Kasikorn Bank
      customerEmail: 'test@example.com',
      customerPhone: '0812345678',
      remark: 'NASKI代付接口测试'
    };

    console.log('正在发送代付请求...');
    const response = await naskiService.createPayoutOrder(payoutRequest);

    console.log('\n【代付下单响应】');
    console.log(JSON.stringify(response, null, 2));

    if (response.code === 200) {
      console.log('\n✅ 代付下单成功!');
      console.log(`   平台订单号: ${response.data?.orderNo}`);
      console.log(`   订单状态: ${response.data?.status} (${naskiService.parseOrderStatus(response.data?.status || 0)})`);
      console.log(`   业务错误码: ${response.data?.subCode || '无'}`);
      console.log(`   业务错误信息: ${response.data?.subMsg || '无'}`);
    } else {
      console.log('\n❌ 代付下单失败');
      console.log(`   错误码: ${response.code}`);
      console.log(`   错误信息: ${response.msg}`);
    }

    // 测试订单查询
    if (response.code === 200 && response.data?.orderNo) {
      console.log('\n5. 测试订单查询...');
      console.log(`正在查询订单: ${testOrderId}`);

      const queryResponse = await naskiService.queryPayoutOrder(testOrderId);

      console.log('\n【订单查询响应】');
      console.log(JSON.stringify(queryResponse, null, 2));

      if (queryResponse.code === 200) {
        console.log('\n✅ 订单查询成功!');
        console.log(`   订单状态: ${queryResponse.data?.status} (${naskiService.parseOrderStatus(queryResponse.data?.status || 0)})`);
      } else {
        console.log('\n❌ 订单查询失败');
        console.log(`   错误码: ${queryResponse.code}`);
        console.log(`   错误信息: ${queryResponse.msg}`);
      }
    }

    console.log('\n========================================');
    console.log('测试完成');
    console.log('========================================');

  } catch (error) {
    console.error('\n❌ 测试过程中发生错误:');
    if (error instanceof Error) {
      console.error(`   错误信息: ${error.message}`);
      console.error(`   错误堆栈:\n${error.stack}`);
    } else {
      console.error(error);
    }
    process.exit(1);
  }
}

// 测试签名生成
function testSignatureGeneration() {
  console.log('\n========================================');
  console.log('签名生成测试');
  console.log('========================================\n');

  const testParams = {
    bankCode: '004',
    name: 'Test User',
    merNo: '12345',
    merOrderNo: 'TEST123456789',
    email: 'test@example.com',
    phone: '0812345678',
    orderAmount: '100',
    currency: 'THB',
    busiCode: '102001',
    pageUrl: 'https://example.com/success',
    notifyUrl: 'https://example.com/notify',
    timestamp: '1704067200000'
  };

  console.log('【待签名参数】');
  console.log(JSON.stringify(testParams, null, 2));

  // 按ASCII排序并拼接
  const sortedKeys = Object.keys(testParams).sort();
  const queryString = sortedKeys.map(key => `${key}=${(testParams as any)[key]}`).join('&');

  console.log('\n【签名原始字符串】');
  console.log(queryString);

  console.log('\n✅ 签名生成逻辑测试完成');
  console.log('注意: 实际签名需要使用商户密钥进行HmacSHA256加密');
}

// 主函数
async function main() {
  // 如果传入参数 --signature，则只测试签名生成
  if (process.argv.includes('--signature')) {
    testSignatureGeneration();
    return;
  }

  // 否则执行完整测试
  await testNaskiPayout();
}

// 运行测试
main().catch(error => {
  Logger.error('测试脚本执行失败', error);
  process.exit(1);
});